package com.csmht.tododemo.aspect;

import com.csmht.tododemo.annotation.AutoFill;
import com.csmht.tododemo.constant.AutoFillConstant;
import com.csmht.tododemo.pojo.enumeration.OperationType;
import com.csmht.tododemo.until.BaseUnit;
import lombok.extern.slf4j.Slf4j;

import org.apache.ibatis.binding.MapperMethod;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.List;

import static com.csmht.tododemo.constant.AutoFillConstant.SET_CREATE_TIME;
import static com.csmht.tododemo.constant.AutoFillConstant.SET_CREATE_USER;

/**
 * 自定义切面，实现公共段自动填充,注意实体类必须放在mapper首个参数，且必须有
 */
@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    /**
     * 切入点
     */
    @Pointcut("execution(* com.csmht.tododemo.mapper.*.*(..)) && @annotation(com.csmht.tododemo.annotation.AutoFill)")
    public void autoFillPointCut(){}

    /**
     * 通知
     */

    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint){
        log.info("AutoFill start");

        Object[] args = joinPoint.getArgs();

        LocalDateTime now = LocalDateTime.now();
        Long userId = BaseUnit.getCurrentId();

        MethodSignature signature =(MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();

        try {
            if(args.length == 0 || args[0] == null){
                return;
            }

            Object arg = args[0];

            if (operationType == OperationType.ONE) {
                Method setTime = arg.getClass().getMethod(SET_CREATE_TIME, LocalDateTime.class);
                Method setUser = arg.getClass().getMethod(SET_CREATE_USER, Long.class);

                setTime.invoke(arg,now);
                setUser.invoke(arg,userId);
            }else if(operationType == OperationType.LIST && arg instanceof List<?> list){
                list.forEach(item ->{
                    try {
                        Method setTime = item.getClass().getMethod(SET_CREATE_TIME, LocalDateTime.class);
                        Method setUser = item.getClass().getMethod(SET_CREATE_USER, Long.class);

                        setTime.invoke(item,now);
                        setUser.invoke(item,userId);
                    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                });

            }

        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }


    }

}
